# Create Sihe Think Tank shortcut with custom icon
# Usage: Right-click -> Run with PowerShell

$ErrorActionPreference = "Continue"
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8

Write-Host "========================================" -ForegroundColor Cyan
Write-Host "  Create Sihe Think Tank Shortcut" -ForegroundColor Cyan
Write-Host "========================================" -ForegroundColor Cyan
Write-Host ""

# Get script directory
$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path

# Find bat file (handle encoding issues with Chinese filenames)
# Priority: 启动思和智库.bat > 启动系统.bat > any other bat
$batFile = $null
$preferredNames = @("启动思和智库.bat", "启动系统.bat")
foreach ($name in $preferredNames) {
    $testPath = Join-Path $scriptDir $name
    if (Test-Path $testPath) {
        $batFile = $testPath
        Write-Host "[INFO] Found startup file: $name" -ForegroundColor Green
        break
    }
}

# If not found, search for any bat file containing keywords
if (-not $batFile) {
    $batFiles = Get-ChildItem -Path $scriptDir -Filter "*.bat" | Where-Object { 
        $_.Name -match "启动|思和|start" 
    }
    if ($batFiles.Count -gt 0) {
        $batFile = $batFiles[0].FullName
        Write-Host "[INFO] Found startup file: $($batFiles[0].Name)" -ForegroundColor Green
    }
}

# Last resort: any bat file
if (-not $batFile) {
    $batFiles = Get-ChildItem -Path $scriptDir -Filter "*.bat" | Sort-Object Length
    if ($batFiles.Count -gt 0) {
        $batFile = $batFiles[0].FullName
        Write-Host "[WARN] Using first bat file found: $($batFiles[0].Name)" -ForegroundColor Yellow
    }
}

if (-not $batFile -or -not (Test-Path $batFile)) {
    Write-Host "[ERROR] Cannot find startup bat file in: $scriptDir" -ForegroundColor Red
    Write-Host ""
    Write-Host "Press any key to exit..." -ForegroundColor Yellow
    $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit 1
}

$iconFile = Join-Path $scriptDir "sihe-icon.ico"

# Check if icon file exists, create if not
if (-not (Test-Path $iconFile)) {
    Write-Host "[INFO] Icon file not found, creating..." -ForegroundColor Yellow
    
    # Create SVG icon
    $svgContent = @"
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256">
  <defs>
    <linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
      <stop offset="0%" style="stop-color:#6366F1;stop-opacity:1" />
      <stop offset="50%" style="stop-color:#A855F7;stop-opacity:1" />
      <stop offset="100%" style="stop-color:#EC4899;stop-opacity:1" />
    </linearGradient>
    <filter id="shadow">
      <feGaussianBlur in="SourceAlpha" stdDeviation="4"/>
      <feOffset dx="0" dy="2" result="offsetblur"/>
      <feComponentTransfer>
        <feFuncA type="linear" slope="0.3"/>
      </feComponentTransfer>
      <feMerge>
        <feMergeNode/>
        <feMergeNode in="SourceGraphic"/>
      </feMerge>
    </filter>
  </defs>
  
  <rect width="256" height="256" rx="48" fill="url(#grad)"/>
  
  <path d="M 40 128 Q 80 80, 120 128 T 200 128" 
        stroke="rgba(255,255,255,0.3)" 
        stroke-width="8" 
        fill="none" 
        stroke-linecap="round"/>
  <path d="M 50 128 Q 90 100, 130 128 T 210 128" 
        stroke="rgba(255,255,255,0.2)" 
        stroke-width="6" 
        fill="none" 
        stroke-linecap="round"/>
  
  <text x="128" y="180" 
        font-family="Microsoft YaHei, Arial, sans-serif" 
        font-size="140" 
        font-weight="bold" 
        fill="white" 
        text-anchor="middle" 
        filter="url(#shadow)">思</text>
  
  <circle cx="80" cy="80" r="8" fill="rgba(255,255,255,0.6)"/>
  <circle cx="176" cy="80" r="6" fill="rgba(255,255,255,0.5)"/>
  <circle cx="128" cy="60" r="5" fill="rgba(255,255,255,0.4)"/>
</svg>
"@
    
    $svgFile = Join-Path $scriptDir "sihe-icon.svg"
    try {
        $svgContent | Out-File -FilePath $svgFile -Encoding UTF8 -NoNewline
        Write-Host "[OK] SVG icon created: $svgFile" -ForegroundColor Green
    } catch {
        Write-Host "[ERROR] Failed to create SVG: $_" -ForegroundColor Red
    }
    
    # Try to convert SVG to ICO using Python
    $pythonScript = Join-Path $scriptDir "create_icon.py"
    if (Test-Path $pythonScript) {
        Write-Host "[INFO] Converting SVG to ICO using Python..." -ForegroundColor Green
        $backendDir = Join-Path $scriptDir "backend"
        $venvPython = Join-Path $backendDir "venv\Scripts\python.exe"
        
        if (Test-Path $venvPython) {
            try {
                & $venvPython $pythonScript 2>&1 | Out-Host
                if (Test-Path $iconFile) {
                    Write-Host "[OK] ICO icon created: $iconFile" -ForegroundColor Green
                } else {
                    Write-Host "[WARN] ICO conversion may have failed" -ForegroundColor Yellow
                }
            } catch {
                Write-Host "[WARN] Python conversion failed: $_" -ForegroundColor Yellow
            }
        } else {
            Write-Host "[WARN] Virtual environment not found, trying system Python..." -ForegroundColor Yellow
            $pythonCmd = Get-Command python -ErrorAction SilentlyContinue
            if ($pythonCmd) {
                try {
                    & python $pythonScript 2>&1 | Out-Host
                } catch {
                    Write-Host "[WARN] System Python conversion failed: $_" -ForegroundColor Yellow
                }
            } else {
                Write-Host "[INFO] Python not found, please convert SVG to ICO manually" -ForegroundColor Yellow
                Write-Host "[INFO] Online tools:" -ForegroundColor Cyan
                Write-Host "      https://convertio.co/zh/svg-ico/" -ForegroundColor Cyan
                Write-Host "      https://cloudconvert.com/svg-to-ico" -ForegroundColor Cyan
            }
        }
    } else {
        Write-Host "[WARN] create_icon.py not found" -ForegroundColor Yellow
        Write-Host "[INFO] Please convert SVG to ICO manually using online tools" -ForegroundColor Cyan
    }
}

# Create shortcut
$desktopPath = [Environment]::GetFolderPath("Desktop")
$shortcutPath = Join-Path $desktopPath "Sihe Think Tank.lnk"

Write-Host ""
Write-Host "[INFO] Creating shortcut..." -ForegroundColor Cyan

try {
    $WshShell = New-Object -ComObject WScript.Shell
    $shortcut = $WshShell.CreateShortcut($shortcutPath)
    $shortcut.TargetPath = $batFile
    $shortcut.WorkingDirectory = $scriptDir
    $shortcut.Description = "Sihe Think Tank - Startup"
    
    # Set icon if exists
    if (Test-Path $iconFile) {
        $shortcut.IconLocation = "$iconFile,0"
        Write-Host "[OK] Custom icon set" -ForegroundColor Green
    } else {
        Write-Host "[WARN] Icon file not found, using default icon" -ForegroundColor Yellow
        Write-Host "[INFO] You can manually set icon later by:" -ForegroundColor Cyan
        Write-Host "      1. Right-click shortcut -> Properties" -ForegroundColor Cyan
        Write-Host "      2. Click 'Change Icon'" -ForegroundColor Cyan
        Write-Host "      3. Browse to: $iconFile" -ForegroundColor Cyan
    }
    
    $shortcut.Save()
    
    Write-Host ""
    Write-Host "[SUCCESS] Shortcut created successfully!" -ForegroundColor Green
    Write-Host "  Location: $shortcutPath" -ForegroundColor Cyan
    Write-Host ""
    
} catch {
    Write-Host ""
    Write-Host "[ERROR] Failed to create shortcut: $_" -ForegroundColor Red
    Write-Host ""
}

Write-Host "Press any key to exit..." -ForegroundColor Yellow
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
